<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-menu"></i>{{$route.name}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="handle-box">
            <el-dialog title="新增角色" :visible.sync="dialogFormVisible">
                <el-form :model="addForm" :rules="rules" size="small" ref="addForm">
                    <el-form-item label="角色名" :label-width="formLabelWidth" prop="name">
                        <el-input v-model="addForm.name" placeholder="请输入内容"></el-input>
                    </el-form-item>
                    <el-form-item label="角色类型" :label-width="formLabelWidth" prop="flag">
                        <el-radio v-model="addForm.flag" label="0">后台角色</el-radio>
                        <el-radio v-model="addForm.flag" label="1">前台角色</el-radio>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="add">确 定</el-button>
                </div>
            </el-dialog>
            <el-dialog title="修改角色" :visible.sync="dialogFormUpdate">
                <el-form :model="upForm" :rules="rules" size="small" ref="upForm">
                    <el-form-item label="角色名" :label-width="formLabelWidth" prop="name">
                        <el-input v-model="upForm.name" placeholder="请输入内容"></el-input>
                    </el-form-item>
                    <el-form-item label="角色类型" :label-width="formLabelWidth" prop="flag">
                        <el-radio v-model="upForm.flag" label="0">后台角色</el-radio>
                        <el-radio v-model="upForm.flag" label="1">前台角色</el-radio>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormUpdate = false">取 消</el-button>
                    <el-button type="primary" @click="modifyRole">确 定</el-button>
                </div>
            </el-dialog>
            <el-dialog :title="privilegeTitle" :visible.sync="dialogAddPrivilege">
                <el-form :model="privilege" :rules="rules" ref="privilege">
                    <el-form-item :label="privilegeTitle" :label-width="formLabelWidth" prop="privilegeId">
                        <el-select v-model="privilege.privilegeId" multiple placeholder="请添加权限">
                            <el-option v-for="value in privileges" :key="value.id" :label="value.p_name" :value="value.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogAddPrivilege = false">取 消</el-button>
                    <el-button type="primary" @click="makePrivilege">确 定</el-button>
                </div>
            </el-dialog>
            <el-input v-model="select_word" placeholder="输入角色名" class="search"></el-input>
            <el-button type="primary" icon="search" @click="search">搜索</el-button>
            <el-button type="primary" @click="dialogFormVisible = true">新增角色</el-button>
        </div>
        <div>
            <el-table :data="tableData" border fit style="width: 100%">
                <el-table-column prop="id" label="角色id">
                </el-table-column>
                <el-table-column prop="role_name" label="角色">
                </el-table-column>
                <el-table-column prop="privilege_list" label="权限" :formatter="formatPro">
                </el-table-column>
                <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
                        <el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button type="text" size="small" @click="delRole(scope.row)">删除</el-button>
                        <el-button type="text" size="small" @click="addPrivilege(scope.row)">
                            {{ scope.row.privilege_list.length === 0 ?  '添加权限' : '修改权限' }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="block">
            <el-pagination @current-change="handleCurrentChange" :current-page="page.number" 
            layout="total, prev, pager, next, jumper" :total="page.total">
            </el-pagination>
        </div>
    </div>
</template>
<script>
import { getAllRoles, delRole, updateRole, addRole, user } from "../../server/getDate.js";
import { mapState, mapActions } from 'vuex'
import { getStore } from '../../utils/local.js'
import { confirm } from '../../utils/local'
const { privilegeList, addPrivilegeToRole } = user
export default {
    data() {
        return {
            value: '',
            loading: false,
            dialogTableVisible: false,
            dialogFormVisible: false,
            dialogFormUpdate: false,
            dialogAddPrivilege: false,
            select_word: '',
            upForm: {
                name: '',
                id: '',
                flag: ''
            },
            addForm: {
                name: '',
                flag: ''
            },
            formLabelWidth: '90px',
            rules: {
                name: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
                flag: [{ required: true, message: '请选择角色类型', trigger: 'blur' }],
                privilegeId: [{ required: true, message: '请添加权限', trigger: 'blur' }],

            },
            privilege: {
                privilegeName: '',
                id: '',
                privilegeId: []
            },
            privilegeTitle: ''
        }
    },
    created() {
        this.getRoles(1)
    },
    computed: mapState({
        page: state => state.Role.page,
        tableData: state => state.Role.roles,
        privileges: state => state.Role.privileges
    }),
    methods: {
        ...mapActions(['saveRole', 'privilege_list']),
        getRoles(number) {
            const obj = {
                page: number,
                pageSize: 10
            }
            if (this.select_word) {
                obj.searchKey = this.select_word
            }
            getAllRoles({ ...obj}).then(res => {
                    if (res.code === '000000') {
                        this.saveRole({
                            ...res,
                            number
                        })
                    }
                })
        },
        handleClick(row) {
            console.log(row)
        },
        formatPro(row, col) {
            let pros = row.privilege_list
            if (pros.length > 0) {
                const names = pros.map(item => {
                    return item.p_name
                })
                return names.join(',')
            } else {
                return '无权限'
            }
        },
        search() {
            this.getRoles(this.page.number)
        },
        handleCurrentChange(val) {
            this.getRoles(val)
        },
        delRole(row) {
            this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let id = row.id
                delRole({ id })
                    .then(res => {
                        if (res.code === '000000') {
                            this.getRoles(this.page.number)
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        add() {
            this.$refs['addForm'].validate((valid) => {
                if (valid) {
                    const role = {
                        roleName: this.addForm.name,
                        flag: this.addForm.flag
                    }
                    addRole({ ...role })
                        .then(res => {
                            if (res.code === '000000') {
                                this.dialogFormVisible = false
                                this.$message.info("添加成功")
                                this.addForm = {}
                                if (this.page.number >= this.page.total / this.tableData.length) {
                                    this.getRoles(this.page.number)
                                } else {
                                    this.getRoles(this.page.number + 1)
                                }
                            } else {
                                this.$message.error(res.message)
                            }
                        }, err => this.$message.error("网络异常"))                    
                }
            })
        },
        edit(row) {
            this.dialogFormUpdate = true
            this.upForm.name = row.role_name
            this.upForm.id = row.id
            this.upForm.flag = row.flag
        },
        modifyRole() {
            this.$refs['upForm'].validate((valid) => {
                if (valid) {
                    let roleEntity = this.upForm
                    updateRole({ 
                        id: roleEntity.id,
                        roleName: roleEntity.name,
                        flag: roleEntity.flag
                    })
                        .then(res => {
                            if (res.code === '000000') {
                                this.dialogFormUpdate = false
                                this.getRoles(this.page.number)
                            } else {
                                this.$message.error(res.message)
                            }
                        }, err => this.$message.error(err.message)) 
                }
            })
        },
        addPrivilege(row) {
            this.privilege.id = row.id
            this.dialogAddPrivilege = true
            if (row.privilege_list.length === 0) {
                this.privilege.privilegeId = []
                this.privilegeTitle = '添加权限'
            } else {
                this.privilegeTitle = '编辑权限'
                this.privilege.privilegeId = row.privilege_list.map(item => {
                    return item.id
                })
            }
            privilegeList({
                page: 1,
                pageSize: 1000
            }).then(res => {
                if (res.code === '000000') {
                    this.privilege_list(res)
                } else {
                    this.$message.error(res.message)
                }
            }, err => this.$message.error(res.message))
        },
        makePrivilege() {
            this.$refs['privilege'].validate(valid => {
                if (valid) {
                    addPrivilegeToRole({
                        roleId: this.privilege.id,
                        privilegeId: this.privilege.privilegeId.join(',')
                    }).then(res => {
                        if (res.code === '000000') {
                            this.privilege.privilegeId = []
                            this.dialogAddPrivilege = false
                            this.$message.success('权限变更成功')
                            this.getRoles(this.page.number)
                        } else {
                            this.$message.error(res.message)
                        }
                    }, err => this.$message.error(res.message))
                }
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 1%;
  .search {
    width: 30%;
  }
}


:global {
    .el-select {
        width: 400px;
    }
    .el-input {
        width: 400px;
    }
}

.block {
  text-align: center;
  margin-top: 1%;
}
</style>